package top.jacktgq.itheima.netty.protocol_design.redis;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @Author CandyWall
 * @Date 2021/3/23--23:57
 * @Description
 */
@Slf4j
public class TestRedis {
    /**
     * 示例：set name zhangsan 指令可以解析为如下协议步骤
     * -> *3 表示接下来要发送三个字符串
     * -> $3 第1个字符串的长度
     * -> set 第1个字符串的内容
     * -> $4 第2个字符串的长度
     * -> name 第2个字符串的内容
     * -> $8 第3个字符串的长度
     * -> zhangsan 第3个字符串的内容
     */
    public static void main(String[] args) throws InterruptedException {
        // 回车和换行的ASCII值分别为13和10
        final byte[] LINE_BREAK = {13, 10};
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG)).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                log.debug("连接已经建立...");
                                ByteBuf buffer = ctx.alloc().buffer();
                                // 验证登录密码
                                buffer.writeBytes("*2".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("$4".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("auth".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("$6".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("123456".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                // 保存数据
                                buffer.writeBytes("*3".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("$3".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("set".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("$4".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("name".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("$8".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                buffer.writeBytes("zhangsan".getBytes());
                                buffer.writeBytes(LINE_BREAK);
                                ctx.writeAndFlush(buffer);
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug("redis服务器回复结果：{}", byteBuf.toString(Charset.defaultCharset()));
                                ctx.close();
                            }
                        });
                    }
                })
                .connect("114.215.211.1", 6379).sync();
        log.debug("连接成功...");
        Channel channel = channelFuture.channel();

        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("客户端正在关闭...");
                group.shutdownGracefully();
                        /*Future<?> f = group.shutdownGracefully();
                        f.addListener(f1 -> {
                            System.out.println(f.get());
                            if (f == f1)
                                System.out.println("closed");
                            else {
                                System.out.println("cannot close");
                            }
                        });*/
                log.debug("客户端已关闭！");
            }
        });

        // 优雅退出group有点问题，需要获取group.shutdownGracefully()方法的返回值的future再get一下就可以退出进程了。
        /*channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("连接成功...");
                Channel channel = future.channel();

                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        log.debug("客户端正在关闭...");
                        group.shutdownGracefully();
                        *//*Future<?> f = group.shutdownGracefully();
                        f.addListener(f1 -> {
                            System.out.println(f.get());
                            if (f == f1)
                                System.out.println("closed");
                            else {
                                System.out.println("cannot close");
                            }
                        });*//*
                        log.debug("客户端已关闭！");
                    }
                });
            }
        });*/
    }
}
